﻿using OA.Models;
using System.Data.Entity.Validation;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web.Mvc;

namespace OA.Controllers
{
    public class BaseController : Controller
    {
        protected OAContext Context = new OAContext();

        public static UserInfo CurrentUser
        {
            get
            {
                return (System.Web.HttpContext.Current.User as CurrentUserCookie).CurrentUser;

                //return new UserInfo()
                //{
                //    UserId = "0",
                //    Department = "管理员",
                //    Post = "管理员",
                //    Name = "管理员",
                //};
            }
        }

        /// <summary>
        ///  返回成功提示信息
        /// </summary>
        /// <param name="message">消息</param>
        /// <returns></returns>
        public AjaxResult Success(string message, object data = null)
        {
            return new AjaxResult(true, message, data);
        }

        /// <summary>
        ///  返回错误提示信息
        /// </summary>
        /// <param name="message">消息</param>
        /// <returns></returns>
        public AjaxResult Failed(string message, object data = null)
        {
            return new AjaxResult(false, message, data);
        }

        /// <summary>
        ///  重写 Json 方法
        ///  避免出现循环引用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="contentType"></param>
        /// <param name="contentEncoding"></param>
        /// <param name="behavior"></param>
        /// <returns></returns>
        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new JsonNetResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior
            };
        }



        /// <summary>
        ///  操作过滤器
        ///  在 Action 方法之前执行
        ///  其约定:
        ///     进行模型验证
        ///     如果有传输模型且不符合验证的
        ///     一律在视图上返回错误信息
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // 模型验证
            // 在请求控制器绑定模型时就触发
            // Api 模型验证失败的话, 直接就返回一个
            if (!ModelState.IsValid)
            {
                var error = ModelState.Values.Where(d => d.Errors.Any()).FirstOrDefault();

                if (error != null)
                {
                    if (Request.IsAjaxRequest())
                    {
                        filterContext.Result = Json(Failed(error.Errors[0].ErrorMessage));
                    }
                    else
                    {
                        ModelState.AddModelError("", error.Errors[0].ErrorMessage);
                        filterContext.Result = View();
                    }
                }
            }
        }

        /// <summary>
        ///  错误处理
        ///  其约定:
        ///     任何没经过处理的错误
        ///     都以 JSon 弹出框的形式在界面上展示
        ///     并生成错误日志
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnException(ExceptionContext filterContext)
        {
            // 最好可以生成一个唯一数据, 方便进行查看
            var result = Failed("操作失败! 请联系管理员");
            var stack = filterContext.Exception.StackTrace;
            var message = filterContext.Exception.Message;


            filterContext.Result = Json(result);
            //当结果为json时，设置异常已处理
            filterContext.ExceptionHandled = true;
        }
    }
}